package com.zretc.controller;

import com.github.pagehelper.PageInfo;
import com.zretc.entity.*;
import com.zretc.service.FilmRankService;
import com.zretc.service.FilmService;
import com.zretc.util.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

@Controller
@RequestMapping("back")
@MultipartConfig
public class BackFilmController {

    @Autowired
    private FilmService filmService;

    @GetMapping("/film")
    @ResponseBody
    public Map<String, Object> getFilmByFilmId(@RequestParam("filmId") String filmId) {
        Map<String, Object> filmByFilmId = filmService.getFilmByFilmId(Integer.valueOf(filmId));

        return filmByFilmId;
    }

    @GetMapping("/filmList")
    @ResponseBody
    public PageInfo<Film> getFilmByCondition(@RequestParam("page") String pageNum,
                                             @RequestParam("limit") String pageSize,
                                   String filmName,
                                   String filmReleaseTime,
                                   String filmStatus) {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum",pageNum);
        map.put("pageSize",pageSize);
        map.put("filmName",filmName);
        map.put("filmReleaseTime",filmReleaseTime);
        map.put("filmStatus",filmStatus);
        PageInfo<Film> filmPageInfo = filmService.getFilmByCondition(map);

        return filmPageInfo;
    }
    @PostMapping("/insertFilm")
    public String insertFilm(@RequestParam("filmName") String filmName,
                              @RequestParam("filmContent") String filmContent,
                              @RequestParam("filmRunTime") String filmRunTime,
                              @RequestParam("filmReleaseTime") String filmReleaseTime,
                              MultipartFile addfilmCover,
                              MultipartFile addfilmPrevue,
                              String filmTypeName1,
                              String filmTypeName2,
                              String filmTypeName3,
                              String actorname1,
                              String actorname2,
                              String actorname3
                              ) {


        Film film = new Film();
        film.setFilmName(filmName);
        film.setFilmContent(filmContent);
        film.setFilmRunTime(filmRunTime);
        film.setFilmReleaseTime(filmReleaseTime);

        // 接收图片
        if (addfilmCover.getSize() == 0) {
           film.setFilmCover(null);
        } else {
            // 1、获取文件名
            String fileFilmCoverName = addfilmCover.getOriginalFilename();
            // 自定义文件名 + 文件后缀名
            // 1.1 获取文件后缀名
            String fileFilmCoverSuffix = fileFilmCoverName.substring(fileFilmCoverName.lastIndexOf("."));
            // 1.2 时间戳自定义文件名
            String dataStamp = System.currentTimeMillis() + "";
            // 1.3 存储文件名
            String filmCover = dataStamp + fileFilmCoverSuffix;
            // 2.将文件存储到指定的目录中
            // 将文件存储在指定的服务器中（本地电脑D盘）
            File f = new File("D:/upload/image/" + filmCover);
            try {
                addfilmCover.transferTo(f);
            } catch (IOException e) {
                e.printStackTrace();
            }
            film.setFilmCover(filmCover);
        }

        // 接收预告片
        if (addfilmPrevue.getSize() == 0) {
            film.setFilmPrevue(null);
        } else {
            // 1、获取文件名
            String fileFilmPrevueName = addfilmPrevue.getOriginalFilename();
            // 自定义文件名 + 文件后缀名
            // 1.1 获取文件后缀名
            String fileFilmPrevueSuffix = fileFilmPrevueName.substring(fileFilmPrevueName.lastIndexOf("."));
            // 1.2 时间戳自定义文件名
            String dataStamp = System.currentTimeMillis() + "";
            // 1.3 存储文件名
            String filmPrevue = dataStamp + fileFilmPrevueSuffix;
            // 2.将文件存储到指定的目录中
            // 将文件存储在指定的服务器中（本地电脑D盘）
            File f = new File("D:/upload/video/" + filmPrevue);
            try {
                addfilmPrevue.transferTo(f);
            } catch (IOException e) {
                e.printStackTrace();
            }
            film.setFilmPrevue(filmPrevue);
        }

        film.setFilmStatus(0);

        List<FilmType> filmTypeList = new ArrayList<>();
        if (filmTypeName1 != null && !"".equals(filmTypeName1)) {
            FilmType filmType1 = new FilmType();
            filmType1.setFilmTypeName(filmTypeName1);
            filmTypeList.add(filmType1);
        }
        if (filmTypeName2 != null && !"".equals(filmTypeName2)) {
            FilmType filmType2 = new FilmType();
            filmType2.setFilmTypeName(filmTypeName2);
            filmTypeList.add(filmType2);
        }
        if (filmTypeName3 != null && !"".equals(filmTypeName3)) {
            FilmType filmType3 = new FilmType();
            filmType3.setFilmTypeName(filmTypeName3);
            filmTypeList.add(filmType3);
        }
        film.setFilmTypeList(filmTypeList);

        List<Actor> actorList = new ArrayList<>();
        if (actorname1 != null && !"".equals(actorname1)) {
            Actor actor1 = new Actor();
            actor1.setActorName(actorname1);
            actorList.add(actor1);
        }
        if (actorname2 != null && !"".equals(actorname2)) {
            Actor actor2 = new Actor();
            actor2.setActorName(actorname2);
            actorList.add(actor2);
        }
        if (actorname3 != null && !"".equals(actorname3)) {
            Actor actor3 = new Actor();
            actor3.setActorName(actorname3);
            actorList.add(actor3);
        }
        film.setActorList(actorList);

        boolean b = filmService.insertFilm(film);
        if (b == true) {
            return "redirect:views/film/film.jsp";
        } else {
            return "上传失败！";
        }
    }

    @DeleteMapping("/deleteFilm/{filmId}")
    @ResponseBody
    public boolean deleteFilmByFilmId(@PathVariable("filmId") String id) {

        Integer filmId = Integer.valueOf(id);
        boolean b = filmService.deleteFilmByFilmId(filmId);
        if (b == true) {
            return true;

        } else {
            return false;
        }
    }

    @PutMapping("/updateFilm")
    @ResponseBody
    public boolean updateFilmByFilmId(@RequestParam("filmId") String filmId,
                                      @RequestParam("filmName") String filmName,
                                      @RequestParam("filmContent") String filmContent,
                                      @RequestParam("filmRunTime") String filmRunTime,
                                      @RequestParam("filmReleaseTime") String filmReleaseTime,
                                      @RequestParam("filmCover") String filmCover,
                                      @RequestParam("filmPrevue") String filmPrevue,
                                      @RequestParam("filmStatus") String filmStatus) {

        Film film = new Film();
        film.setFilmId(Integer.valueOf(filmId));
        film.setFilmName(filmName);
        film.setFilmContent(filmContent);
        film.setFilmRunTime(filmRunTime);
        film.setFilmReleaseTime(filmReleaseTime);
        film.setFilmCover(filmCover);
        film.setFilmPrevue(filmPrevue);

        film.setFilmStatus(Integer.valueOf(filmStatus));

        boolean b = filmService.updateFilmByFilmId(film);
        if (b == true) {
            return true;
        } else {
            return false;
        }
    }

    @GetMapping("/exportFilm")
    @ResponseBody
    public void fileExportFilm(HttpServletResponse response) throws IOException {
        // 标题内容（可在前端设置，通过参数传递进来）
        // key是实体类的属性值，value是表头的lable
        Map<String, String> head = new LinkedHashMap<>();
        head.put("filmId","影片编号");
        head.put("filmName","影片名称");
        head.put("filmContent","影片简介");
        head.put("filmRunTime","播放时长");
        head.put("filmReleaseTime","上映时间");
        head.put("filmCover","影片封面名称");
        head.put("filmPrevue","影片预告片名称");

        // 表格数据内容-数据集查询出来的数据
        List<Film> data = new ArrayList<>();

        List<Film> filmList = filmService.getFilmListByexport();
        for (Film film : filmList) {
            Integer filmId = film.getFilmId();
            String filmName = film.getFilmName();
            String filmContent = film.getFilmContent();
            String filmRunTime = film.getFilmRunTime();
            String filmReleaseTime = film.getFilmReleaseTime();
            String filmCover = film.getFilmCover();
            String filmPrevue = film.getFilmPrevue();
            Integer filmStatus = film.getFilmStatus();
            data.add(new Film(filmId,filmName,filmContent,filmRunTime,filmReleaseTime,filmCover,filmPrevue,filmStatus));
        }

        // 生成工作簿
        HSSFWorkbook hssfWorkbook = ExcelUtil.creatExcel(head,data);

        // 定义文件名
        String fileName = "影片信息表";

        // 下载
        // 设置响应头
        response.setHeader("Cache-Control","max-age=0");
        // 设置响应类型为excel
        response.setContentType("application/vnd.mx-excel");
        // 设置文件头编码方式和文件名
        response.addHeader("Content-disposition",
                "attachment;filename=" + new String(fileName.getBytes("gb2312"),"ISO-8859-1") + ".xls");
        OutputStream outputStream = response.getOutputStream();
        hssfWorkbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
